const {
    add,
    del,
    edit,
    search,
    searchBy
} = require('../js/mysql.js');

const jwtAuth = require("../jwtAuth")


const router = require('koa-router')()

router.prefix('/newsList')

router.use(jwtAuth)


router.get("/search", async (ctx) => {
    let data = await search("news");
    ctx.body = {
        msg: '操作成功',
        code: 200,
        data,
    }
})


//增加
router.post('/addnews', async function (ctx, next) {
    let { body } = ctx.request;
    let { title, author, date, content } = body;
    let data = await add([title, author, date, content], `news(title, author,date, content) VALUES(?,?,?,?)`);
    ctx.body = {
        msg: '添加成功',
        code: 200,
        data
    }
})


//查看全部内容
router.get('/content', async function (ctx, next) {
    // 获取页码数据，并指定默认值
    const { page, limit } = ctx.request.query;
    let data = await search(`news LIMIT ${(page * 1-1) * limit},${limit * 1}`);
    // console.log(48,data);
    let data1 = await search("news");
    data.unshift(data1.length);
    ctx.body = {
        msg: '操作成功',
        code: 200,
        data
    }
})


//修改
router.put('/', async function (ctx, next) {
    let { body } = ctx.request;
    let { id } = ctx.query;
    console.log(62,id);
    let { title,date, author, content } = body;
    let data = await edit([title, date, author, content], `id=${id}`, "news");
    ctx.body = {
        msg: '修改成功',
        code: 200,
        data
    }
})


router.delete('/delete', async function (ctx, next) {
    let { id } = ctx.query;
    console.log(74,id);
    let data = await del(`id=${id}`, "news");
    ctx.body = {
        msg: '删除成功',
        code: 200,
        data
    }
})
module.exports = router